// 功能点：
// 1. "我的喜欢"
// 2. "我的歌单"
// 3. 新建歌单



// "我的喜欢"字样
const myLikeSong = document.querySelector('.user-likes-nav');
// "我的歌单"字样
const myPlaylist = document.querySelector('.user-playlists-nav');
// "我的喜欢"信息页
const likesPlaylistsMiddleArea = document.querySelector('.likes-playlists-middle-area');
// "我的歌单"信息页
const userPlaylistsMiddleArea = document.querySelector('.user-playlists-middle-area');
// 每个歌单信息页
const playlistDetailMiddleArea = document.querySelector('.playlist-detail-middle-area');



// 点击"我的喜欢"，切换页面
myLikeSong.addEventListener('click', () => {
    likesPlaylistsMiddleArea.style.display = 'block';
    userPlaylistsMiddleArea.style.display = 'none';
    playlistDetailMiddleArea.style.display = 'none';

    myLikeSong.className = 'user-likes-nav default-select';
    myPlaylist.className = 'user-playlists-nav';
})



// 点击"我的歌单"，切换页面
myPlaylist.addEventListener('click', () => {
    userPlaylistsMiddleArea.style.display = 'block';
    likesPlaylistsMiddleArea.style.display = 'none';
    playlistDetailMiddleArea.style.display = 'none';

    myPlaylist.className = 'user-playlists-nav default-select';
    myLikeSong.className = 'user-likes-nav';
})



// 1. "我的喜欢"



// 获取歌单基本信息(无法获取歌单里歌曲)
function userPlaylist(userId) {
    ajaxRequest({
        url: `${defaultUrlHeader}/user/playlist`,

        data: {
            uid: userId
        },

        success: function (responseText) {
            console.log('获取该用户歌单id成功');
            console.log(responseText);

            // 渲染用户歌单
            userCreatePlaylists(responseText.playlist, userId);
        },

        error: function (xhr) {
            console.log('获取该用户歌单id失败');
            console.log(xhr.readyState);
            console.log(xhr.status);
        }
    });
}



// 获取用户喜欢音乐的id列表
function userLikelist(userId) {
    ajaxRequest({
        url: `${defaultUrlHeader}/likelist`,

        data: {
            uid: userId
        },

        success: function (responseText) {
            console.log('获取用户喜欢音乐id成功');
            console.log(responseText);

            // 利用id获取用户喜欢音乐信息
            userLikeSongs(responseText.ids, userId);
        },

        error: function (xhr) {
            console.log('获取用户喜欢音乐id失败');
            console.log(xhr.readyState);
            console.log(xhr.status);
        }
    });
}



// 利用id获取用户喜欢音乐信息
function userLikeSongs(ids, userId) {
    ajaxRequest({
        url: `${defaultUrlHeader}/song/detail`,

        data: {
            ids: ids
        },

        success: function (responseText) {
            console.log('获取用户喜欢音乐信息成功');
            console.log(responseText);

            // 渲染用户喜欢的音乐
            userLikeSongsRender(responseText.songs, userId);
        },

        error: function (xhr) {
            console.log('获取用户喜欢音乐信息失败');
            console.log(xhr.readyState);
            console.log(xhr.status);
        }
    });
}



// "我的喜欢"ul box
let likeBox = document.querySelector('.like-box');
// "我的喜欢"单曲行样板节点
let likeItemSample = document.querySelector('.like-item');



// 渲染用户喜欢的音乐
function userLikeSongsRender(songs, userId) {
    if (songs) {
        // 先删除原有的所有单曲行节点
        let eachLikeItems = document.querySelectorAll('.like-item');
        // 这里要先保存删除前ul的子元素的长度
        // 因为在删除过程中，长度会变化
        let childrenLength = likeBox.children.length;
        if (childrenLength > 1) {
            // "1"是因为样板节点不能删
            // 条件成立说明之前渲染过，用户喜欢的列表不为空
            for (let i = 1; i < childrenLength; i++) {
                eachLikeItems[i].parentNode.removeChild(eachLikeItems[i]);
            }
        }

        // 采用克隆节点的方法
        let songLength = songs.length;
        for (let i = 0; i < songLength - 1; i++) {
            // 深拷贝，拷贝样板节点的所有子节点
            let likeItem = likeItemSample.cloneNode(true);
            likeBox.appendChild(likeItem);
        }

        // 单曲序号
        let likeCounts = document.querySelectorAll('.item-count');
        // 单曲名
        let likeItemNames = document.querySelectorAll('.item-name');
        // 单曲歌手
        let likeItemPlayers = document.querySelectorAll('.item-player');
        // 单曲专辑
        let likeItemAlbums = document.querySelectorAll('.item-album');

        for (let i = 0; i < songLength; i++) {
            // 渲染基本信息
            likeCounts[i].innerHTML = i + 1;
            likeItemNames[i].innerHTML = songs[i].name;
            likeItemPlayers[i].innerHTML = songs[i].ar[0].name;
            likeItemAlbums[i].innerHTML = getTime(songs[i].publishTime);

            // 点击单曲名，跳转至音乐信息页面
            likeItemNames[i].addEventListener('click', () => {

                searchFocus.innerHTML = songs[i].name;
                userInfPage.style.display = 'none';
                searchArea.style.display = 'block';
                resultMiddleArea.style.display = 'block';
                resultMainAreaSongs.style.display = 'none';
                songDisplayArea.style.display = 'block';

                // 导航栏切换
                topNavLis[0].className = 'default-selected';
                topNavLis[1].className = '';

                // 获取单曲详细信息
                songDetail(songs[i].id, userId);
                // 获取单曲评论
                songComments(songs[i].id);
            })
        }
    } else {
        likeItemSample.innerHTML = '无喜欢的歌曲';
    }
}



// 2. "我的歌单"



// 歌单行盒子
let myPlaylistsEachLine = document.querySelector('.my-playlists-each-line');



// 渲染用户歌单
function userCreatePlaylists(playlist, userId) {

    // 先删除原有的所有歌单行节点
    let playlistLineItem = document.querySelectorAll('.my-playlists-line-item'),
        lineLength = myPlaylistsEachLine.children.length;

    for (let i = 0; i < lineLength; i++) {
        myPlaylistsEachLine.removeChild(playlistLineItem[i]);
    }

    // 再创建新的歌单行节点
    let playlistLength = playlist.length;

    if (playlistLength !== 0) {
        for (let i = 0; i < playlistLength; i++) {

            // 创建li节点
            let playlistItem = document.createElement('li');
            myPlaylistsEachLine.appendChild(playlistItem);
            playlistItem.className = 'my-playlists-line-item';

            // 创建歌单图片节点
            let playlistPic = document.createElement('div');
            playlistItem.appendChild(playlistPic);
            playlistPic.className = 'each-playlist-pic';
            playlistPic.style.backgroundImage = `url(${playlist[i].coverImgUrl})`;

            // 创建歌单名节点
            let playlistName = document.createElement('div');
            playlistItem.appendChild(playlistName);
            playlistName.className = 'each-playlist-name';
            playlistName.innerHTML = playlist[i].name;

            // 创建曲目数节点
            let playlistNum = document.createElement('div');
            playlistItem.appendChild(playlistNum);
            playlistNum.className = 'each-playlist-num';
            playlistNum.innerHTML = `${playlist[i].trackCount}首`;

            // 创建播放量节点
            let playlistCount = document.createElement('div');
            playlistItem.appendChild(playlistCount);
            playlistCount.className = 'each-playlist-count';
            playlistCount.innerHTML = playlist[i].playCount;

            // 点击歌单名，跳转至歌单信息页面
            playlistName.addEventListener('click', () => {
                playlistDetailMiddleArea.style.display = 'block';
                userPlaylistsMiddleArea.style.display = 'none';

                // 更新歌单播放量
                updatePlaylist(playlist[i].id);
                // 获取歌单详细信息
                userPlaylistDetail(playlist[i].id, userId);
            });
        }
    }
}



// 更新歌单播放量
function updatePlaylist(playlistId) {
    ajaxRequest({
        url: `${defaultUrlHeader}/playlist/update/playcount`,

        data: {
            id: playlistId
        },

        success: function (responseText) {
            console.log('更新歌单播放量成功');
            console.log(responseText);
        },

        error: function (xhr) {
            console.log('更新歌单播放量失败');
            console.log(xhr.readyState);
            console.log(xhr.status);
        }
    })
}



// 获取歌单详细信息的函数(获取歌单里的歌曲)
function userPlaylistDetail(playlistId, userId) {
    ajaxRequest({
        url: `${defaultUrlHeader}/playlist/detail`,

        data: {
            id: playlistId
        },

        success: function (responseText) {
            console.log('获取歌单详细信息成功');
            console.log(responseText);

            // 渲染歌单信息页
            renderPlaylistPage(responseText.playlist, userId);
        },

        error: function (xhr) {
            console.log('获取歌单详细信息失败');
            console.log(xhr.readyState);
            console.log(xhr.status);
        }
    });
}



// 歌单图片
let playlistPicture = document.querySelector('.playlist-picture');
// 歌单名
let playlistSingleName = document.querySelector('.playlist-name');
// 歌单播放量
let playlistPlayCount = document.querySelector('.playlist-play-count');
// 歌曲box
let songUl = document.querySelector('.playlist-song-box');



// 渲染歌单信息页
function renderPlaylistPage(playlist, userId) {

    // 渲染基本信息
    playlistPicture.style.backgroundImage = `url(${playlist.coverImgUrl})`;
    playlistSingleName.innerHTML = playlist.name;
    playlistPlayCount.innerHTML = `播放量：${playlist.playCount}`;

    // 先删除原有的所有单曲行节点
    let songItem = document.querySelectorAll('.playlist-song-line'),
        lineLength = songUl.children.length;

    for (let i = 0; i < lineLength; i++) {
        songUl.removeChild(songItem[i]);
    }

    // 再创建新的单曲行节点
    let playlistTracksLength = playlist.tracks.length;

    if (playlistTracksLength !== 0) {

        for (let i = 0; i < playlistTracksLength; i++) {

            // 创建li节点
            let songLi = document.createElement('li');
            songUl.appendChild(songLi);
            songLi.className = 'playlist-song-line';

            // 创建序号节点
            let songNum = document.createElement('div');
            songLi.appendChild(songNum);
            songNum.className = 'playlist-song-num';
            songNum.innerHTML = i + 1;

            // 创建歌名节点
            let songName = document.createElement('div');
            songLi.appendChild(songName);
            songName.className = 'playlist-song-name';
            songName.innerHTML = playlist.tracks[i].name;

            // 创建歌手节点
            let songPlayer = document.createElement('div');
            songLi.appendChild(songPlayer);
            songPlayer.className = 'playlist-song-player';
            songPlayer.innerHTML = playlist.tracks[i].ar[0].name;

            // 创建专辑节点
            let songAlbum = document.createElement('div');
            songLi.appendChild(songAlbum);
            songAlbum.className = 'playlist-song-album';
            songAlbum.innerHTML = playlist.tracks[i].al.name;

            // 点击歌名，跳转至音乐信息页面
            songName.addEventListener('click', () => {

                searchFocus.innerHTML = playlist.tracks[i].name;
                userInfPage.style.display = 'none';
                searchArea.style.display = 'block';
                resultMiddleArea.style.display = 'block';
                resultMainAreaSongs.style.display = 'none';
                songDisplayArea.style.display = 'block';

                // 导航栏切换
                topNavLis[0].className = 'default-selected';
                topNavLis[1].className = '';

                // 获取单曲详细信息
                songDetail(playlist.tracks[i].id, userId);
                // 获取单曲评论
                songComments(playlist.tracks[i].id);
            })
        }
    }
}



// 3. 新建歌单



// "新建歌单"按钮
let createPlaylistBtn = document.querySelector('.create-new-playlist-btn');
// "新建歌单"盒子
let createPlaylistBox = document.querySelector('.create-box');
// 关闭按钮
let createBoxCloseBtn = document.querySelector('.create-box-close');
// 歌单名输入框
let playlistNameBox = document.querySelector('.create-playlist-name');
// 剩余字数
let restCount = document.querySelector('.rest-count');
// 超字数提示
let aboveWarning = document.querySelector('.above-warning');
// 取消按钮
let cancelBtn = document.querySelector('.cancel-create-btn');
// 确定按钮
let certainBtn = document.querySelector('.certain-create-btn');



// 点击"新建歌单"弹出盒子
createPlaylistBtn.addEventListener('click', () => {
    createPlaylistBox.style.display = 'block';
})



// 点击"X"关闭盒子
createBoxCloseBtn.addEventListener('click', () => {
    playlistNameBox.value = '';
    createPlaylistBox.style.display = 'none';
})



// 点"取消"关闭盒子
cancelBtn.addEventListener('click', () => {
    playlistNameBox.value = '';
    createPlaylistBox.style.display = 'none';
})



// 输入时反馈剩余字数
playlistNameBox.addEventListener('input', function () {
    restCount.innerHTML = 20 - playlistNameBox.value.length;
    // 超出字数，颜色变红
    restCount.style.color = restCount.innerHTML < 0 ? 'red' : '#999';
})



// 输入框获得焦点
playlistNameBox.addEventListener('focus', () => {
    aboveWarning.style.display = 'none';
})



// 点击"确定"，验证字数
certainBtn.addEventListener('click', () => {
    let playlistName = playlistNameBox.value,
        wordCount = 20 - playlistNameBox.value.length;

    if (wordCount < 0) {
        aboveWarning.style.display = 'block';
    } else {
        // 新建歌单
        createPlaylist(playlistName);
    }
})



// 新建歌单
function createPlaylist(playlistName) {
    ajaxRequest({
        url: `${defaultHeader}/playlist/create`,

        data: {
            name: playlistName
        },

        success: function (responseText) {
            console.log('新建歌单成功');
            console.log(responseText);

            // 清除输入、关闭新建歌单盒子
            playlistNameBox.value = '';
            createPlaylistBox.style.display = 'none';
        },

        error: function (xhr) {
            console.log('新建歌单失败');
            console.log(xhr.readyState);
            console.log(xhr.status);
        }
    });
}